package com.glory.hikvisionmobile.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.EqpCheckListAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.bean.EqpManger.EqpCheckBean;
import com.glory.hikvisionmobile.bean.EqpManger.EqpCheckListBean;
import com.glory.hikvisionmobile.bean.TrackIn.ItemWorkBean;
import com.glory.hikvisionmobile.bean.from.LocationBean;
import com.glory.hikvisionmobile.bean.from.LocationListBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Eqp_EqpCheckActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {


    @BindView(R.id.tvRegion)
    TextView tvRegion;
    @BindView(R.id.ivRegionListArrow)
    ImageView ivRegionListArrow;
    @BindView(R.id.flRegionList)
    FrameLayout flRegionList;
    @BindView(R.id.tvWork)
    TextView tvWork;
    @BindView(R.id.ivWorkListArrow)
    ImageView ivWorkListArrow;
    @BindView(R.id.flWorkList)
    FrameLayout flWorkList;
    @BindView(R.id.tvFuture)
    TextView tvFuture;
    @BindView(R.id.ivFutureListArrow)
    ImageView ivFutureListArrow;
    @BindView(R.id.flFutureList)
    FrameLayout flFutureList;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.list_tv5)
    TextView listTv5;
    @BindView(R.id.rvWorkCheckList)
    RecyclerView rvWorkCheckList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.cbCreate)
    CheckBox cbCreate;
    @BindView(R.id.cbComplete)
    CheckBox cbComplete;
    @BindView(R.id.cbSave)
    CheckBox cbSave;
    private List<String> locationList = new ArrayList();
    private FreeUI_GeneralPop locationPop;
    private String location;
    private FreeUI_GeneralPop futurePop;
    private List<String> subEquipmentId = new ArrayList<>();
    private FreeUI_GeneralPop eqpIdPop;
    private EqpCheckListAdapter eqpCheckListAdapter;
    @BindView(R.id.nsScroll)
    NestedScrollView nsScroll;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_eqp_check;
    }

    @Override
    protected void initView() {
        initListView();

        rvWorkCheckList.setLayoutManager(new LinearLayoutManager(Eqp_EqpCheckActivity.this));
        rvWorkCheckList.setItemAnimator(new DefaultItemAnimator());
        rvWorkCheckList.addItemDecoration(new DividerItemDecoration(Eqp_EqpCheckActivity.this, 1));
        eqpCheckListAdapter = new EqpCheckListAdapter(null, true);
        eqpCheckListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        eqpCheckListAdapter.isFirstOnly(true);
        rvWorkCheckList.setAdapter(eqpCheckListAdapter);

        eqpCheckListAdapter.setOnItemClickListener(this);
    }

    private void initListView() {
        listTv1.setVisibility(View.VISIBLE);
        listTv2.setVisibility(View.VISIBLE);
        listTv3.setVisibility(View.VISIBLE);
        listTv4.setVisibility(View.VISIBLE);
        listTv5.setVisibility(View.VISIBLE);
        listTv1.setText("序号");
        listTv2.setText("点检内容");
        listTv3.setText("点检时间");
        listTv4.setText("设备");
        listTv5.setText("状态");
    }

    @Override
    protected void initData() {
        NetUtils.requestDara("HIK.PdaBaseLocation", this, null, new FreeUI_DialogEntityCallBack<BaseResponseBean<LocationListBean>>
                (new TypeToken<BaseResponseBean<LocationListBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LocationListBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    locationList.clear();
                    List<LocationBean> locationBeans = response.body().getBody().getxPdaLocations();
                    for (LocationBean bean : locationBeans) {
                        locationList.add(bean.getName() + "/" + bean.getDescription());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LocationListBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaBaseLocation");
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("设备点检");
        freeUI_titleView.setRightListener("隐藏", v -> {

            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    nsScroll.setVisibility(nsScroll.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                }
            });

        });
        return new FreeUI_AddViewEntity("header", llMain);
    }


    @OnClick({R.id.flRegionList, R.id.flWorkList, R.id.flFutureList, R.id.tvSearch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flRegionList:
                if (locationList.size() <= 0) {
                    showToast("未获取到区域列表，请刷新后重试", false);
                    return;
                }

                if (locationPop != null) {
                    if (locationPop.isShowing()) {
                        locationPop.dismiss();
                    }
                } else {
                    locationPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flRegionList.getWidth(), locationList, ivRegionListArrow, (code, i) -> {
                        tvRegion.setText(code);
                        location = code.split("/")[0];
                        requestEqpList(location);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivRegionListArrow);
                locationPop.showAsDropDown(flRegionList, 0, 0);
                break;
            case R.id.flWorkList:
                if (subEquipmentId.size() <= 0) {
                    showToast("未获取到设备信息，请选择区域后重新获取", false);
                    return;
                }

                if (eqpIdPop != null) {
                    if (eqpIdPop.isShowing()) {
                        eqpIdPop.dismiss();
                    }
                } else {
                    eqpIdPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flWorkList.getWidth(), subEquipmentId, ivWorkListArrow, (code, i) -> {
                        tvWork.setText(code);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivWorkListArrow);
                eqpIdPop.showAsDropDown(flWorkList, 0, 0);
                break;
            case R.id.flFutureList:
                if (futurePop != null) {
                    if (futurePop.isShowing()) {
                        futurePop.dismiss();
                    }
                } else {
                    futurePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flFutureList.getWidth(), getFutureList(), ivFutureListArrow, (code, i) -> {
                        tvFuture.setText(code);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivFutureListArrow);
                futurePop.showAsDropDown(flFutureList, 0, 0);
                break;
            case R.id.tvSearch:

                initPermission("Submit", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        search();
                    }
                });

                break;
        }
    }

    private void requestEqpList(String area) {
        tvWork.setText("");
        if (subEquipmentId.size() > 0) {
            subEquipmentId.clear();
        }
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "getEqpsBySpotEqp");
        map.addProperty("area", area);
        NetUtils.requestDara("HIK.PdaGetSubEqp", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<ItemWorkBean>>
                (new TypeToken<BaseResponseBean<ItemWorkBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ItemWorkBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    subEquipmentId.addAll(response.body().getBody().getSubEquipmentId());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ItemWorkBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaGetSubEqp");
            }
        });
    }

    private void search() {
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "query");
        map.addProperty("eqpId", tvWork.getText().toString().trim());
        map.addProperty("area", location);
//        map.addProperty("futureHours",future);
//        map.addProperty("status","CREATE");
        NetUtils.requestDara("HIK.PdaSpotCheckSchedule", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpCheckBean>>
                (new TypeToken<BaseResponseBean<EqpCheckBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EqpCheckBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    List<EqpCheckListBean> eqpCheckListBeans = response.body().getBody().getxPdaSpotCheckScheduleResults();
                    List<EqpCheckListBean> checkData = new ArrayList<>();
                    checkData.clear();
                    if (eqpCheckListBeans.size() <= 0) {
                        showConfirmDialog("暂无点检计划");
                        eqpCheckListAdapter.setNewData(null);
                    } else {
                        if (!cbComplete.isChecked() & !cbCreate.isChecked() & !cbSave.isChecked()){
                            nsScroll.setVisibility(View.GONE);
                            eqpCheckListAdapter.setNewData(eqpCheckListBeans);
                        }else {
                            for (EqpCheckListBean data : eqpCheckListBeans){
                                String status = data.getStatus();
                                if (cbCreate.isChecked()){
                                    if (status.equals("CREATE") | status.equals("WARNING")
                                            | status.equals("CANSTART") | status.equals("START")){
                                        checkData.add(data);
                                    }
                                }

                                if (cbComplete.isChecked()){
                                    if (status.equals("COMPLETE")){
                                        checkData.add(data);
                                    }
                                }

                                if (cbSave.isChecked()){
                                    if (status.equals("FORM")){
                                        checkData.add(data);
                                    }
                                }
                            }

                            if (checkData.size() <= 0){
                                showConfirmDialog("当前状态下无点检计划");
                                eqpCheckListAdapter.setNewData(null);
                            }else {
                                nsScroll.setVisibility(View.GONE);
                                eqpCheckListAdapter.setNewData(checkData);
                            }
                        }

                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EqpCheckBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaSpotCheckSchedule");
            }
        });
    }

    private List<String> getFutureList() {
        List<String> list = new ArrayList<>();
        list.add("2");
        list.add("4");
        list.add("8");
        list.add("12");
        list.add("24");
        return list;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        search();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        EqpCheckListBean item = eqpCheckListAdapter.getData().get(position);
        switch (item.getStatus()) {
            case "CREATE"://创建
            case "WARNING"://警告
            case "CANSTART"://可以开始
                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "是否开始设备点检?", () -> {
                    JsonObject map = new JsonObject();
                    map.addProperty("actionType", "startSchedule");
                    map.addProperty("scheduleRrn", item.getObjectRrn());
                    NetUtils.requestDara("HIK.PdaSpotCheckSchedule", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>(
                            new TypeToken<BaseResponseBean<?>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<?>> response) {
                            super.onSuccess(response);
                            if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                item.setStatus("START");
                                adapter.notifyItemChanged(position);
                                Bundle bundle = new Bundle();
                                bundle.putString("scheduleRrn", item.getObjectRrn());
                                FreeApi_Utils.skipWithExtraIntent("header", bundle, Eqp_EqpCheckActivity.this, Eqp_EqpCheckDetailsActivity.class);

                            }
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<?>> response) {
                            super.onError(response);
                            loadError(response.getException(), "HIK.PdaSpotCheckSchedule");
                        }
                    });
                }, () -> {
                }).show(getSupportFragmentManager(), "EQPKEEP");
                break;
            case "START"://已开始
            case "FORM"://已临时保存
                Bundle bundle = new Bundle();
                bundle.putString("scheduleRrn", item.getObjectRrn());
                FreeApi_Utils.skipWithExtraIntent("header", bundle, Eqp_EqpCheckActivity.this, Eqp_EqpCheckDetailsActivity.class);
                break;
            case "COMPLETE"://已完成
                showToast("当前点检项已完成", false);
                break;
            case "TIMEOUT"://超时
                showToast("当前点检项已超时", false);
                break;
            default:
                break;
        }
    }
}
